﻿namespace CP.NLayer.Client.WpfClient.Common
{
    using System.Windows;
    using Telerik.Windows.Controls;

    /// <summary>
    /// See http://blog.excastle.com/2010/07/25/mvvm-and-dialogresult-with-no-code-behind/
    /// </summary>
    public static class DialogCloser
    {
        public static readonly DependencyProperty MyDialogResultProperty =
            DependencyProperty.RegisterAttached("MyDialogResult", typeof(bool?), typeof(DialogCloser), new PropertyMetadata(MyDialogResultChanged));

        public static readonly DependencyProperty RadDialogResultProperty =
            DependencyProperty.RegisterAttached("RadDialogResult", typeof(bool?), typeof(DialogCloser), new PropertyMetadata(RadDialogResultChanged));

        public static bool GetMyDialogResult(DependencyObject obj)
        {
            return (bool)obj.GetValue(MyDialogResultProperty);
        }

        public static void SetMyDialogResult(Window target, bool? value)
        {
            target.SetValue(MyDialogResultProperty, value);
        }

        public static bool GetRadDialogResult(DependencyObject obj)
        {
            return (bool)obj.GetValue(RadDialogResultProperty);
        }

        public static void SetRadDialogResult(DependencyObject obj, bool value)
        {
            obj.SetValue(RadDialogResultProperty, value);
        }

        private static void MyDialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var window = d as Window;
            if (window != null)
            {
                window.DialogResult = e.NewValue as bool?;
            }
        }

        private static void RadDialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var window = d as RadWindow;
            if (window != null)
            {
                window.DialogResult = e.NewValue as bool?;
                if (window.DialogResult.HasValue)
                {
                    window.Close();
                }
            }
        }
    }
}